package ui

import (
	"lnzw/engine/log"

	"go.uber.org/zap"
)

type EventType int

type IEvent interface {
}

type EventHandle func(event IEvent)

type EventMgr struct {
	handles map[EventType][]*EventHandle
}

func NewEventMgr() *EventMgr {
	return &EventMgr{
		handles: make(map[EventType][]*EventHandle),
	}
}

func (p *EventMgr) Register(eventType EventType, handle *EventHandle) {
	handles, ok := p.handles[eventType]
	if !ok {
		handles = make([]*EventHandle, 0)
	}
	handles = append(handles, handle)
	p.handles[eventType] = handles
}

// 触发事件
func (p *EventMgr) Dispatch(eventType EventType, event IEvent) {
	defer func() {
		if err := recover(); err != nil {
			log.Error("event handle panic", zap.Error(err.(error)))
		}
	}()
	handles, ok := p.handles[eventType]
	if !ok {
		return
	}
	for _, handle := range handles {
		(*handle)(event)
	}
}

// 取消注册
func (p *EventMgr) UnRegister(eventType EventType, handle *EventHandle) {
	handles, ok := p.handles[eventType]
	if !ok {
		return
	}
	for i, h := range handles {
		if h == handle {
			handles = append(handles[:i], handles[i+1:]...)
			break
		}
	}
	p.handles[eventType] = handles
}

// 全局事件
var GlobalEventMgr = NewEventMgr()

const (
	EventType_Login     EventType = iota
	EventType_CreateMap EventType = iota
	EventType_GetMap    EventType = iota
)
